<template>
  <div class="payment-voucher-management">
    <a-spin :loading="loading">
      <!-- 操作区域 -->
      <div class="action-bar">
        <a-space>
          <a-button type="primary" @click="showUploadModal">
            <template #icon><IconUpload /></template>
            上传支付凭证
          </a-button>
          <a-button @click="refreshVouchers">
            <template #icon><IconRefresh /></template>
            刷新
          </a-button>
        </a-space>
      </div>

      <!-- 支付凭证列表 -->
      <div class="voucher-list">
        <a-row :gutter="[16, 16]">
          <a-col :span="8" v-for="voucher in vouchers" :key="voucher.voucherId">
            <a-card class="voucher-card" :bordered="true">
              <template #cover>
                <div class="voucher-preview" @click="showPreviewModal(voucher)">
                  <img 
                    v-if="isImageFile(voucher.fileType)"
                    :src="voucher.thumbnailUrl || voucher.fileUrl"
                    :alt="voucher.fileName"
                    class="voucher-image"
                  />
                  <div v-else class="voucher-file">
                    <IconFile class="file-icon" />
                    <div class="file-type">{{ voucher.fileType.toUpperCase() }}</div>
                  </div>
                  <div class="preview-overlay">
                    <IconEye class="preview-icon" />
                  </div>
                </div>
              </template>
              
              <template #actions>
                <a-space>
                  <a-button type="text" size="small" @click="showPreviewModal(voucher)">
                    <IconEye />预览
                  </a-button>
                  <a-button type="text" size="small" @click="downloadVoucher(voucher)">
                    <IconDownload />下载
                  </a-button>
                  <a-popconfirm
                    content="确定要删除这个支付凭证吗？"
                    @ok="deleteVoucher(voucher)"
                  >
                    <a-button type="text" size="small" status="danger">
                      <IconDelete />删除
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
              
              <a-card-meta
                :title="voucher.fileName"
                :description="getVoucherDescription(voucher)"
              >
                <template #avatar>
                  <a-tag :color="getVoucherTypeColor(voucher.voucherType)">
                    {{ getVoucherTypeText(voucher.voucherType) }}
                  </a-tag>
                </template>
              </a-card-meta>
              
              <div class="voucher-info">
                <div class="info-item">
                  <span class="info-label">文件大小：</span>
                  <span class="info-value">{{ voucher.fileSize }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">上传时间：</span>
                  <span class="info-value">{{ voucher.uploadTime }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">上传人：</span>
                  <span class="info-value">{{ voucher.uploader }}</span>
                </div>
              </div>
            </a-card>
          </a-col>
          
          <!-- 空状态 -->
          <a-col :span="24" v-if="vouchers.length === 0">
            <a-empty description="暂无支付凭证">
              <a-button type="primary" @click="showUploadModal">
                <template #icon><IconUpload /></template>
                上传支付凭证
              </a-button>
            </a-empty>
          </a-col>
        </a-row>
      </div>
    </a-spin>

    <!-- 上传凭证弹窗 -->
    <a-modal
      v-model:visible="uploadModalVisible"
      title="上传支付凭证"
      width="600px"
      @ok="handleUploadSubmit"
      @cancel="resetUploadForm"
    >
      <a-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" layout="vertical">
        <a-form-item field="voucherType" label="凭证类型" required>
          <a-select v-model="uploadForm.voucherType" placeholder="请选择凭证类型">
            <a-option value="BANK_RECEIPT">银行回单</a-option>
            <a-option value="TRANSFER_VOUCHER">转账凭证</a-option>
            <a-option value="PAYMENT_SLIP">付款单据</a-option>
            <a-option value="INVOICE">发票</a-option>
            <a-option value="CONTRACT">合同</a-option>
            <a-option value="OTHER">其他</a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item field="relatedPaymentNoticeId" label="关联支付通知">
          <a-select 
            v-model="uploadForm.relatedPaymentNoticeId" 
            placeholder="请选择关联的支付通知" 
            allow-clear
            @change="handlePaymentNoticeChange"
          >
            <a-option
              v-for="notice in paymentNotices"
              :key="notice.subsidyApplicationPayNoticeId"
              :value="notice.subsidyApplicationPayNoticeId"
            >
              {{ notice.noticeDate }} - {{ notice.payExplain || '支付通知' }}
            </a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item field="relatedPaymentId" label="关联支付记录">
          <a-select v-model="uploadForm.relatedPaymentId" placeholder="请选择关联的支付记录" allow-clear>
            <a-option
              v-for="record in filteredPaymentRecords"
              :key="record.subsidyApplicationPayRecordId"
              :value="record.subsidyApplicationPayRecordId"
            >
              {{ record.payDate }} - {{ record.payType }} ¥{{ record.payMoney }}万元
            </a-option>
          </a-select>
        </a-form-item>
        
        <a-form-item field="description" label="凭证说明">
          <a-textarea
            v-model="uploadForm.description"
            placeholder="请输入凭证说明"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
        
        <a-form-item field="files" label="上传文件" required>
          <a-upload
            ref="uploadRef"
            :file-list="uploadForm.files"
            :auto-upload="false"
            :multiple="true"
            :limit="5"
            accept=".jpg,.jpeg,.png,.pdf,.doc,.docx"
            @change="handleFileChange"
          >
            <template #upload-button>
              <div class="upload-area">
                <IconPlus class="upload-icon" />
                <div class="upload-text">点击上传文件</div>
                <div class="upload-tip">支持 JPG、PNG、PDF、DOC 格式，最多5个文件</div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 预览弹窗 -->
    <a-modal
      v-model:visible="previewModalVisible"
      :title="previewVoucher?.fileName"
      width="800px"
      :footer="false"
    >
      <div class="preview-content">
        <img 
          v-if="previewVoucher && isImageFile(previewVoucher.fileType)"
          :src="previewVoucher.fileUrl"
          :alt="previewVoucher.fileName"
          class="preview-image"
        />
        <div v-else class="preview-file">
          <IconFile class="preview-file-icon" />
          <div class="preview-file-info">
            <div class="preview-file-name">{{ previewVoucher?.fileName }}</div>
            <div class="preview-file-type">{{ previewVoucher?.fileType.toUpperCase() }} 文件</div>
            <a-button type="primary" @click="downloadVoucher(previewVoucher)">
              <template #icon><IconDownload /></template>
              下载文件
            </a-button>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { Message } from '@arco-design/web-vue';
import {
  IconUpload,
  IconRefresh,
  IconFile,
  IconEye,
  IconDownload,
  IconDelete,
  IconPlus
} from '@arco-design/web-vue/es/icon';

// 定义props
const props = defineProps({
  subsidyApplicationId: {
    type: String,
    required: true
  }
});

// 响应式数据
const loading = ref(false);
const uploadModalVisible = ref(false);
const previewModalVisible = ref(false);
const uploadFormRef = ref(null);
const uploadRef = ref(null);
const vouchers = ref([]);
const previewVoucher = ref(null);
const paymentNotices = ref([]);
const paymentRecords = ref([]);

// 上传表单
const uploadForm = reactive({
  voucherType: '',
  relatedPaymentNoticeId: '',
  relatedPaymentId: '',
  description: '',
  files: []
});

// 表单验证规则
const uploadRules = {
  voucherType: [{ required: true, message: '请选择凭证类型' }],
  files: [{ required: true, message: '请上传文件' }]
};

// 模拟支付通知数据
const mockPaymentNotices = [
  {
    subsidyApplicationPayNoticeId: "notice_001",
    noticeDate: "2024-01-15",
    payExplain: "第一批补贴支付通知",
    totalAmount: 50.0,
    status: "PENDING"
  },
  {
    subsidyApplicationPayNoticeId: "notice_002",
    noticeDate: "2024-02-10",
    payExplain: "第二批补贴支付通知",
    totalAmount: 30.0,
    status: "PROCESSING"
  },
  {
    subsidyApplicationPayNoticeId: "notice_003",
    noticeDate: "2024-03-05",
    payExplain: "第三批补贴支付通知",
    totalAmount: 25.0,
    status: "COMPLETED"
  }
];

// 模拟支付记录数据
const mockPaymentRecords = [
  {
    subsidyApplicationPayRecordId: "PAY001",
    relatedPaymentNoticeId: "notice_001",
    payType: "首次支付",
    payMoney: 20.0,
    payDate: "2024-01-20",
    payMethod: "银行转账",
    status: "COMPLETED"
  },
  {
    subsidyApplicationPayRecordId: "PAY002",
    relatedPaymentNoticeId: "notice_001",
    payType: "二次支付",
    payMoney: 30.0,
    payDate: "2024-01-25",
    payMethod: "银行转账",
    status: "COMPLETED"
  },
  {
    subsidyApplicationPayRecordId: "PAY003",
    relatedPaymentNoticeId: "notice_002",
    payType: "尾款支付",
    payMoney: 30.0,
    payDate: "2024-02-15",
    payMethod: "银行转账",
    status: "PROCESSING"
  },
  {
    subsidyApplicationPayRecordId: "PAY004",
    relatedPaymentNoticeId: "notice_003",
    payType: "补充支付",
    payMoney: 25.0,
    payDate: "2024-03-10",
    payMethod: "银行转账",
    status: "PENDING"
  }
];

// 模拟支付凭证数据
const mockVouchers = [
  {
    voucherId: 'VOUCHER001',
    fileName: '银行转账回单_20240125.pdf',
    fileType: 'pdf',
    fileSize: '1.2MB',
    fileUrl: '#',
    thumbnailUrl: '',
    voucherType: 'BANK_RECEIPT',
    relatedPaymentId: 'PAY001',
    description: '首次支付的银行转账回单',
    uploader: '财务部-李会计',
    uploadTime: '2024-01-25 15:30:00'
  },
  {
    voucherId: 'VOUCHER002',
    fileName: '付款凭证_20240215.jpg',
    fileType: 'jpg',
    fileSize: '2.8MB',
    fileUrl: 'https://via.placeholder.com/400x300/4CAF50/FFFFFF?text=Payment+Voucher',
    thumbnailUrl: 'https://via.placeholder.com/200x150/4CAF50/FFFFFF?text=Payment+Voucher',
    voucherType: 'PAYMENT_SLIP',
    relatedPaymentId: 'PAY002',
    description: '二次支付的付款凭证',
    uploader: '财务部-王出纳',
    uploadTime: '2024-02-15 16:45:00'
  },
  {
    voucherId: 'VOUCHER003',
    fileName: '合同扫描件_森林生态修复.pdf',
    fileType: 'pdf',
    fileSize: '3.5MB',
    fileUrl: '#',
    thumbnailUrl: '',
    voucherType: 'CONTRACT',
    relatedPaymentId: '',
    description: '项目合同扫描件',
    uploader: '项目部-张经理',
    uploadTime: '2024-01-20 10:15:00'
  }
];

// 获取凭证类型文本
const getVoucherTypeText = (type) => {
  const textMap = {
    'BANK_RECEIPT': '银行回单',
    'TRANSFER_VOUCHER': '转账凭证',
    'PAYMENT_SLIP': '付款单据',
    'INVOICE': '发票',
    'CONTRACT': '合同',
    'OTHER': '其他'
  };
  return textMap[type] || '未知';
};

// 获取凭证类型颜色
const getVoucherTypeColor = (type) => {
  const colorMap = {
    'BANK_RECEIPT': 'blue',
    'TRANSFER_VOUCHER': 'green',
    'PAYMENT_SLIP': 'orange',
    'INVOICE': 'purple',
    'CONTRACT': 'cyan',
    'OTHER': 'gray'
  };
  return colorMap[type] || 'gray';
};

// 获取凭证描述
const getVoucherDescription = (voucher) => {
  return voucher.description || '暂无描述';
};

// 判断是否为图片文件
const isImageFile = (fileType) => {
  return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(fileType.toLowerCase());
};

// 计算属性：根据选择的支付通知过滤支付记录
const filteredPaymentRecords = computed(() => {
  if (!uploadForm.relatedPaymentNoticeId) {
    return paymentRecords.value;
  }
  return paymentRecords.value.filter(
    record => record.relatedPaymentNoticeId === uploadForm.relatedPaymentNoticeId
  );
});

// 处理支付通知变化
const handlePaymentNoticeChange = (value) => {
  // 当支付通知变化时，清空已选择的支付记录
  uploadForm.relatedPaymentId = '';
};

// 加载支付凭证
const loadVouchers = () => {
  loading.value = true;
  
  setTimeout(() => {
    vouchers.value = mockVouchers;
    loading.value = false;
  }, 300);
};

// 加载支付通知数据
const loadPaymentNotices = () => {
  paymentNotices.value = mockPaymentNotices;
};

// 加载支付记录数据
const loadPaymentRecords = () => {
  paymentRecords.value = mockPaymentRecords;
};

// 刷新凭证列表
const refreshVouchers = () => {
  loadVouchers();
  Message.success('刷新成功');
};

// 显示上传弹窗
const showUploadModal = () => {
  resetUploadForm();
  uploadModalVisible.value = true;
};

// 预览凭证
const showPreviewModal = (voucher) => {
  previewVoucher.value = voucher;
  previewModalVisible.value = true;
};

// 下载凭证
const downloadVoucher = (voucher) => {
  console.log('下载凭证:', voucher);
  Message.success(`开始下载: ${voucher.fileName}`);
};

// 删除凭证
const deleteVoucher = (voucher) => {
  console.log('删除凭证:', voucher);
  const index = vouchers.value.findIndex(item => item.voucherId === voucher.voucherId);
  if (index > -1) {
    vouchers.value.splice(index, 1);
    Message.success('删除成功');
  }
};

// 处理文件变化
const handleFileChange = (fileList) => {
  uploadForm.files = fileList;
};

// 提交上传表单
const handleUploadSubmit = () => {
  uploadFormRef.value.validate((errors) => {
    if (errors) {
      return;
    }
    
    if (uploadForm.files.length === 0) {
      Message.error('请选择要上传的文件');
      return;
    }
    
    console.log('上传凭证数据:', uploadForm);
    
    // 模拟上传成功
    uploadForm.files.forEach((file, index) => {
      const newVoucher = {
        voucherId: `VOUCHER${Date.now()}_${index}`,
        fileName: file.name,
        fileType: file.name.split('.').pop().toLowerCase(),
        fileSize: `${(file.size / 1024 / 1024).toFixed(1)}MB`,
        fileUrl: URL.createObjectURL(file),
        thumbnailUrl: isImageFile(file.name.split('.').pop()) ? URL.createObjectURL(file) : '',
        voucherType: uploadForm.voucherType,
        relatedPaymentNoticeId: uploadForm.relatedPaymentNoticeId,
        relatedPaymentId: uploadForm.relatedPaymentId,
        description: uploadForm.description,
        uploader: '当前用户',
        uploadTime: new Date().toLocaleString()
      };
      vouchers.value.unshift(newVoucher);
    });
    
    Message.success('上传成功');
    uploadModalVisible.value = false;
    resetUploadForm();
  });
};

// 重置上传表单
const resetUploadForm = () => {
  Object.assign(uploadForm, {
    voucherType: '',
    relatedPaymentNoticeId: '',
    relatedPaymentId: '',
    description: '',
    files: []
  });
  uploadModalVisible.value = false;
};

// 组件挂载时加载数据
onMounted(() => {
  loadVouchers();
  loadPaymentNotices();
  loadPaymentRecords();
});
</script>

<style scoped>
.payment-voucher-management {
  padding: 16px;
}

.action-bar {
  margin-bottom: 16px;
}

.voucher-card {
  height: 100%;
  transition: all 0.3s;
}

.voucher-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.voucher-preview {
  position: relative;
  height: 200px;
  cursor: pointer;
  overflow: hidden;
}

.voucher-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.voucher-file {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background: #f7f8fa;
  color: #86909c;
}

.file-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.file-type {
  font-size: 14px;
  font-weight: 500;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.voucher-preview:hover .preview-overlay {
  opacity: 1;
}

.preview-icon {
  font-size: 32px;
  color: white;
}

.voucher-info {
  margin-top: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 12px;
}

.info-label {
  color: #86909c;
}

.info-value {
  color: #4e5969;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 20px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #165dff;
  background: #f0f5ff;
}

.upload-icon {
  font-size: 32px;
  color: #165dff;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 16px;
  color: #1d2129;
  margin-bottom: 4px;
}

.upload-tip {
  font-size: 12px;
  color: #86909c;
}

.preview-content {
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  border-radius: 6px;
}

.preview-file {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
}

.preview-file-icon {
  font-size: 64px;
  color: #86909c;
  margin-bottom: 16px;
}

.preview-file-info {
  text-align: center;
}

.preview-file-name {
  font-size: 18px;
  font-weight: 500;
  color: #1d2129;
  margin-bottom: 8px;
}

.preview-file-type {
  font-size: 14px;
  color: #86909c;
  margin-bottom: 16px;
}

:deep(.arco-card-meta-title) {
  font-size: 14px;
  font-weight: 500;
}

:deep(.arco-card-meta-description) {
  font-size: 12px;
  color: #86909c;
}

:deep(.arco-card-actions) {
  padding: 12px 16px;
}
</style>